package com.gitee.ywj1352.kafka;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;
import javax.naming.Context;
import javax.naming.InitialContext;

public class ActiveMqMain {

    public static void main(String[] args) throws Exception{

//        Context ctx = new InitialContext();
//        ConnectionFactory cf1 = (ConnectionFactory) ctx.lookup("jms/QueueConnectionFactory");
//        ConnectionFactory cf2 = (ConnectionFactory) ctx.lookup("/jms/TopicConnectionFactory");


        //初始化连接工厂
        ConnectionFactory connectionFactory=new ActiveMQConnectionFactory(ActiveMQConnection.DEFAULT_BROKER_URL);
        //建立连接
        Connection conn= connectionFactory.createConnection();
        //启动连接
        conn.start();
        //获取 回话
        Session session= conn.createSession(false,Session.AUTO_ACKNOWLEDGE);
        //创建目标队列
        //useQueue(session);
        useTopic(session);
    }

    private static void useQueue(Session session) throws JMSException, InterruptedException {
        Destination dest = session.createQueue("YWJ-TEST-QUEUE");
        //通过session创建消息的发送者
        MessageProducer producer= session.createProducer(dest);

        for (int i = 0; i < 10; i++) {
            //定义要发送的消息
            TextMessage message= session.createTextMessage("======ActiveMQ发送消息===="+i+"===");
            //发送消息
            producer.send(message);
            //休眠2秒
            Thread.sleep(2000);
        }
    }


    private static void useTopic(Session session)throws  Exception{
        Topic topic = session.createTopic("YWJ-TEST-TOPIC");
        MessageProducer producer = session.createProducer(topic);
        for (int i = 0; i < 10; i++) {
            System.out.println("====发送====");
            //定义要发送的消息
            TextMessage message= session.createTextMessage("======ActiveMQ发送消息 Topic===="+i+"===");
            //发送消息
            producer.send(message);
            //休眠2秒
            Thread.sleep(2000);
        }
    }


}
